public class MinDistance {

    public static void main(String[] args) {
        MinDistance minDistance = new MinDistance();
        System.out.println(minDistance.minDistance("horse", "ros"));
    }

    public int minDistance(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();
        if (n == 0 || m == 0) return n == 0 ? m : n;
        char[] chars1 = word1.toCharArray();
        char[] chars2 = word2.toCharArray();
        int[][] dp = new int[n][m];
        dp[0][0] = chars1[0] == chars2[0] ? 0 : 1;
        for (int i = 1; i < n; i++) {
            dp[i][0] = chars1[i] == chars2[0] ? i : dp[i - 1][0] + 1;
        }
        for (int i = 1; i < m; i++) {
            dp[0][i] = chars1[0] == chars2[i] ? i : dp[0][i - 1] + 1;
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]) + 1, dp[i - 1][j - 1] + (chars1[i] == chars2[j] ? 0 : 1));
            }
        }
        return dp[n - 1][m - 1];
    }
}
